package com.example.weblending.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.example.weblending.exception.GlobalException;
import com.example.weblending.vo.CsvInputColumn;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Component
public class CsvUtils {

    @Value("${csv-model.input-path}")
    private String inputPath;

    public String upload(MultipartFile file) {
        if (file.isEmpty()){
            throw new GlobalException(404,"文件上传失败");
        }
        String fileName = file.getOriginalFilename(); //获取上传文件原来的名称
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        fileName = uuid+fileName;
        java.io.File temp = new java.io.File(this.inputPath);
        if (!temp.exists()){
            temp.mkdirs();
        }
        java.io.File localFile = new java.io.File(this.inputPath+fileName);
        try {
            file.transferTo(localFile); //把上传的文件保存至本地
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException(30001,"文件上传失败");
        }
        return this.inputPath+fileName;
    }

    public String exportToFile(List data) {
        String path= this.inputPath;
        File myPath = new File( path );
        if ( !myPath.exists()){
            myPath.mkdirs();
        }
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        String fileName = path.concat(uuid).concat(ExcelTypeEnum.CSV.getValue());
        EasyExcel.write(fileName,CsvInputColumn.class).sheet("default").doWrite(data);
        return fileName;
    }


    /**
     * 根据单个条件生成临时的文件
     * @param condition 用户自己输入的条件
     * @return 生成的临时文件路径
     */
    public static String makeCSV(CsvInputColumn condition){
        String path="";
        return path;
    }
}
